package com.yangtu.nearbyshop.db.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangtu.nearbyshop.db.dao.NearbyshopMercMapper2;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.dao.NearbyshopMercRebateMapper;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopMercRebateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 门店返利统计表 服务实现类
 * </p>
 *
 * @author wanglei
 * @since 2019-09-19
 */
@Service
public class NearbyshopMercRebateServiceImpl extends ServiceImpl<NearbyshopMercRebateMapper,
        NearbyshopMercRebate> implements INearbyshopMercRebateService {

    @Autowired
    NearbyshopMercRebateMapper rebateMapper;

    @Autowired
    NearbyshopOrderGoodsService goodsService;

    @Autowired
    NearbyshopGoodsProductService productService;

    @Autowired
    NearbyshopMercMapper2 mercMapper2;

    @Autowired
    NearbyshopUserService userService;

    /**
     * 当交易完成后，38元的售价，成本假如20元，设置的总代提成10元，普通团长4元（这个4元是包含在10元内的）。那所有返利如下：
     * 1.给平台，成本价的20%，4元。
     * 2.给总代，判断该用户的团长，团长级别为总代A，则此单获利总分配额为设置的总代提成10元。
     *      2.1 该总代A的上级为空，则该总代A获得所有的这10元。
     *      2.2 该总代A的上级为普通团长，不存在。
     *      2.3 该总代A的上级为总代B ，则总代A获利9.5元，总代B获利0.5元.（10元分成9.5元与0.5元）
     *          （该总代A的上级为总代B， 则总代B始终获得 总代A每条返利额*5%。（理解为总代A赚的钱要分5%给总代B，这个5%不是平台出的，是总代A出的））   。
     *  
     * 3.给团长，判断该用户的团长，团长级别为普通团长A，则此单获利总分配额为（10元）。
     *      3.1 该普通团长A的上级为空，不存在 一定会有总代或普通团长。
     *      3.2 该普通团长A的上级为普通团长B，这时需要一直向上找到第一个总代C。ABC分这10元。则A获利（4元，设置的普通团长提成）。C获得6元。
     *      3.3 该普通团长A的上级为总代 ，则A获利（4元，设置的普通团长提成），总代获利10元-4元=6元.
     *   
     *  
     * 4.判断用户的团长，如果为空，不存在
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRebateData(NearbyshopOrder order) {
        List<NearbyshopOrderGoods> goodsList = goodsService.queryByOid(order.getId());
        List<NearbyshopMercRebate> rebates = new ArrayList<>();

        for (NearbyshopOrderGoods orderGoods: goodsList) {
            NearbyshopGoodsProduct product = productService.findById(orderGoods.getProductId());
            BigDecimal fl = product.getPlatProfit().multiply(new BigDecimal(orderGoods.getNumber()))
                    .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
            //1.给平台返利
            NearbyshopMercRebate settlePlat = new NearbyshopMercRebate();
            String item = "[\"" + (orderGoods.getGoodsName()+",提成"+product.getPlatProfit()+"*"+"数量"
                    +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
            settlePlat.setAddTime(new Date());
            settlePlat.setAmount(fl);
            settlePlat.setRebateProductId(product.getId());
            settlePlat.setMercNo("platform");
            settlePlat.setRebateOrderId(order.getId());
            settlePlat.setRebateType("ticheng-goods1");
            settlePlat.setRebateDesc("平台提成=成本的20%");
            settlePlat.setItems(item);
            rebates.add(settlePlat);

            //2.给下单用户上级返利
            NearbyshopUser user = userService.findById(order.getUserId());
            NearbyshopMerc2 mercA = mercMapper2.selectOne(new QueryWrapper<NearbyshopMerc2>()
                    .eq("merc_no",user.getMercNo()));
            //该商品总的可分配金额
            BigDecimal totalBenefit = product.getSuperProfit();
            //2:上级为一级总代
            if(mercA == null){
                return;
            }
            if(("101").equals(mercA.getLevel())){
                //2.1 一级总代上级为空
                if(StringUtils.isEmpty(mercA.getReferMerc())){
                    NearbyshopMercRebate settle21 = new NearbyshopMercRebate();
                    item = "[\"" + (orderGoods.getGoodsName()+",提成"+product.getSuperProfit()+"*"+"数量"
                            +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                    fl = totalBenefit.multiply(new BigDecimal(orderGoods.getNumber()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                    settle21.setAddTime(new Date());
                    settle21.setAmount(fl);
                    settle21.setRebateProductId(product.getId());
                    settle21.setMercNo(mercA.getMercNo());
                    settle21.setRebateOrderId(order.getId());
                    settle21.setRebateType("ticheng-goods21");
                    settle21.setRebateDesc("总代提成=总提成额");
                    settle21.setItems(item);
                    rebates.add(settle21);

                } else {
                    //2.3： 给B
                    NearbyshopMerc2 mercB = mercMapper2.selectOne(new QueryWrapper<NearbyshopMerc2>()
                            .eq("merc_no",mercA.getReferMerc()));
                    if(("101").equals(mercB.getLevel())){
                        NearbyshopMercRebate settle23 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成"+product.getSuperProfit()+"*10%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        fl = totalBenefit.divide(new BigDecimal("10")).multiply(new BigDecimal(orderGoods.getNumber()))
                                .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                        settle23.setAddTime(new Date());
                        settle23.setAmount(fl);
                        settle23.setRebateProductId(product.getId());
                        settle23.setMercNo(mercB.getMercNo());
                        settle23.setRebateOrderId(order.getId());
                        settle23.setRebateType("ticheng-goods23B");
                        settle23.setRebateDesc("总代上级提成=总提成额*10%");
                        settle23.setItems(item);
                        rebates.add(settle23);
                    }

                    //2.3： 给A
                    if(("101").equals(mercA.getLevel())){
                        NearbyshopMercRebate settle23 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成"+product.getSuperProfit()+"*90%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        fl = totalBenefit.multiply(new BigDecimal("9")).divide(new BigDecimal("10"))
                                .multiply(new BigDecimal(orderGoods.getNumber()))
                                .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                        settle23.setAddTime(new Date());
                        settle23.setAmount(fl);
                        settle23.setRebateProductId(product.getId());
                        settle23.setMercNo(mercA.getMercNo());
                        settle23.setRebateOrderId(order.getId());
                        settle23.setRebateType("ticheng-goods23A");
                        settle23.setRebateDesc("总代提成=总提成额*90%");
                        settle23.setItems(item);
                        rebates.add(settle23);
                    }
                }
            }else if(("100").equals(mercA.getLevel())){
                //3：上级为普通代理
                NearbyshopMerc2 mercB = mercMapper2.selectOne(new QueryWrapper<NearbyshopMerc2>()
                        .eq("merc_no",mercA.getReferMerc()));
                NearbyshopMerc2 mercC = null;
                //3.2 A的上级为普通B
                if(("100").equals(mercB.getLevel())){
                    //遍历找到B的上级第一个总代C
                    mercC = getMercC(mercB.getReferMerc());
                    //向上找C的上级总代D，只找一级
                    NearbyshopMerc2 mercD = null;
                    if(!StringUtils.isEmpty(mercC.getReferMerc())){
                        mercD = mercMapper2.selectOne(new QueryWrapper<NearbyshopMerc2>()
                                .eq("merc_no",mercC.getReferMerc()));
                    }

                    //总返利额
                    BigDecimal bg = product.getSuperProfit().multiply(new BigDecimal(orderGoods.getNumber()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                    //3.2： 给A
                    NearbyshopMercRebate settle32 = new NearbyshopMercRebate();
                    item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getMercProfit()+")*"+"数量"
                            +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                    BigDecimal fa = product.getMercProfit().multiply(new BigDecimal(orderGoods.getNumber()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                    settle32.setAddTime(new Date());
                    settle32.setAmount(fa);
                    settle32.setRebateProductId(product.getId());
                    settle32.setMercNo(mercA.getMercNo());
                    settle32.setRebateOrderId(order.getId());
                    settle32.setRebateType("ticheng-goods32A");
                    settle32.setRebateDesc("团长提成=团长提成额");
                    settle32.setItems(item);
                    rebates.add(settle32);

                    //3.2： 给B
                    settle32 = new NearbyshopMercRebate();
                    item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                            +"-"+product.getMercProfit()+")*30%*"+"数量"
                            +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                    BigDecimal fb = bg.subtract(fa).multiply(new BigDecimal("0.3"))
                            .setScale(2, BigDecimal.ROUND_HALF_UP)
                            .stripTrailingZeros();
                    settle32.setAddTime(new Date());
                    settle32.setAmount(fb);
                    settle32.setRebateProductId(product.getId());
                    settle32.setMercNo(mercB.getMercNo());
                    settle32.setRebateOrderId(order.getId());
                    settle32.setRebateType("ticheng-goods32B");
                    settle32.setRebateDesc("上级团长提成=（总提成额-团长提成额）*30%");
                    settle32.setItems(item);
                    rebates.add(settle32);

                    //3.2： 给C
                    //如果mercD为空，则C获得剩下的所有
                    if(null == mercD){
                        settle32 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                                +"-"+product.getMercProfit()+")*70%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        BigDecimal fc = bg.subtract(fa).subtract(fb)
                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                .stripTrailingZeros();
                        settle32.setAddTime(new Date());
                        settle32.setAmount(fc);
                        settle32.setRebateProductId(product.getId());
                        settle32.setMercNo(mercC.getMercNo());
                        settle32.setRebateOrderId(order.getId());
                        settle32.setRebateType("ticheng-goods32C-1");
                        settle32.setRebateDesc("总代提成=(总提成额-团长提成额)*70%");
                        settle32.setItems(item);
                        rebates.add(settle32);
                    }else {
                        settle32 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                                +"-"+product.getMercProfit()+")*70%*90%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        BigDecimal fc2 = bg.subtract(fa).subtract(fb).multiply(new BigDecimal("0.9"))
                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                .stripTrailingZeros();
                        settle32.setAddTime(new Date());
                        settle32.setAmount(fc2);
                        settle32.setRebateProductId(product.getId());
                        settle32.setMercNo(mercC.getMercNo());
                        settle32.setRebateOrderId(order.getId());
                        settle32.setRebateType("ticheng-goods32C-2");
                        settle32.setRebateDesc("总代提成=剩余利润*70%*90%");
                        settle32.setItems(item);
                        rebates.add(settle32);

                        settle32 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                                +"-"+product.getMercProfit()+")*70%*10%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        BigDecimal fc = bg.subtract(fa).subtract(fb).subtract(fc2)
                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                .stripTrailingZeros();
                        settle32.setAddTime(new Date());
                        settle32.setAmount(fc);
                        settle32.setRebateProductId(product.getId());
                        settle32.setMercNo(mercD.getMercNo());
                        settle32.setRebateOrderId(order.getId());
                        settle32.setRebateType("ticheng-goods32D-2");
                        settle32.setRebateDesc("总代上级提成=剩余利润*70%*10%");
                        settle32.setItems(item);
                        rebates.add(settle32);
                    }
                }else if(("101").equals(mercB.getLevel())){
                    //总返利额
                    BigDecimal bg = product.getSuperProfit().multiply(new BigDecimal(orderGoods.getNumber()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                    //3.3： 给A
                    NearbyshopMercRebate settle33 = new NearbyshopMercRebate();
                    item = "[\"" + (orderGoods.getGoodsName()+",提成"+product.getMercProfit()+"*"+"数量"
                            +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                    BigDecimal fa = product.getMercProfit().multiply(new BigDecimal(orderGoods.getNumber()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                    settle33.setAddTime(new Date());
                    settle33.setAmount(fa);
                    settle33.setRebateProductId(product.getId());
                    settle33.setMercNo(mercA.getMercNo());
                    settle33.setRebateOrderId(order.getId());
                    settle33.setRebateType("ticheng-goods33A");
                    settle33.setRebateDesc("团长提成=团长提成额");
                    settle33.setItems(item);
                    rebates.add(settle33);

                    //向上找B的上级总代D，只找一级
                    NearbyshopMerc2 mercD = null;
                    if(!StringUtils.isEmpty(mercB.getReferMerc())){
                        mercD = mercMapper2.selectOne(new QueryWrapper<NearbyshopMerc2>()
                                .eq("merc_no",mercB.getReferMerc()));
                    }

                    //3.3： 给B
                    if(null == mercD){
                        //总代B没有上级，总代B获得所有
                        settle33 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                                +"-"+product.getMercProfit()+")*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        BigDecimal fb = bg.subtract(fa)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                        settle33.setAddTime(new Date());
                        settle33.setAmount(fb);
                        settle33.setRebateProductId(product.getId());
                        settle33.setMercNo(mercB.getMercNo());
                        settle33.setRebateOrderId(order.getId());
                        settle33.setRebateType("ticheng-goods33B");
                        settle33.setRebateDesc("总代提成=总提成额-团长提成额");
                        settle33.setItems(item);
                        rebates.add(settle33);
                    }else {
                        //总代B有上级，总代B获得90% ，上级D或者10%
                        settle33 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                                +"-"+product.getMercProfit()+")*90%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        BigDecimal fb = bg.subtract(fa).multiply(new BigDecimal("0.9"))
                                .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                        settle33.setAddTime(new Date());
                        settle33.setAmount(fb);
                        settle33.setRebateProductId(product.getId());
                        settle33.setMercNo(mercB.getMercNo());
                        settle33.setRebateOrderId(order.getId());
                        settle33.setRebateType("ticheng-goods33B-2");
                        settle33.setRebateDesc("总代提成=(总提成额-团长提成额)*90%");
                        settle33.setItems(item);
                        rebates.add(settle33);

                        settle33 = new NearbyshopMercRebate();
                        item = "[\"" + (orderGoods.getGoodsName()+",提成("+product.getSuperProfit()
                                +"-"+product.getMercProfit()+")*10%*"+"数量"
                                +orderGoods.getNumber()+"="+fl.toPlainString()) + "\"]";
                        BigDecimal fd = bg.subtract(fa).subtract(fb)
                                .setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();
                        settle33.setAddTime(new Date());
                        settle33.setAmount(fd);
                        settle33.setRebateProductId(product.getId());
                        settle33.setMercNo(mercB.getMercNo());
                        settle33.setRebateOrderId(order.getId());
                        settle33.setRebateType("ticheng-goods33D-2");
                        settle33.setRebateDesc("总代提成=(总提成额-团长提成额)*10%");
                        settle33.setItems(item);
                        rebates.add(settle33);
                    }

                }
            }

        }

        saveBatch(rebates);
    }

    public NearbyshopMerc2 getMercC(String mercNo){
        if(StringUtils.isEmpty(mercNo)){
            return null;
        }
        NearbyshopMerc2 mercC = mercMapper2.selectOne(new QueryWrapper<NearbyshopMerc2>()
                .eq("merc_no",mercNo));
        if(mercC == null){
            return null;
        }
        if(StringUtils.isEmpty(mercC.getLevel())){
            return null;
        }else if(mercC.getLevel().equals("101")){
            return mercC;
        }else{
            return getMercC(mercC.getReferMerc());
        }
    }

    @Override
    public IPage<NearbyshopMercRebate> getTimeRebate(Page<NearbyshopMercRebate> page,
                                                     String mercName, String mercNo,
                                                     String startTime, String endTime) {
        return rebateMapper.getTimeRebate(page,mercName,mercNo,startTime,endTime);
    }

    @Override
    public IPage<NearbyshopMercRebateSettle> getDailyRebate(Page<NearbyshopMercRebate> page,
                                                     String mercName, String mercNo,
                                                     String startTime, String endTime,Integer adminId) {
        return rebateMapper.getDailyRebate(page,mercName,mercNo,startTime,endTime,adminId);
    }

    @Override
    public String countAllRebate(String mercNo,
                                 String startTime, String endTime) {
        return rebateMapper.countAllRebate(mercNo,startTime, endTime);
    }
}
